/*
  Copyright 2012 Sergey Ostanin

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package ru.irenproject;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

import javax.inject.Inject;
import javax.inject.Singleton;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;

import ru.irenproject.store.AbstractThing;
import ru.irenproject.store.Thing;
import ru.irenproject.store.ThingRegistry;

import com.google.common.collect.ImmutableMap;

@Singleton public final class ActionRegistry {
  private final ImmutableMap<Class<? extends Thing>, ImmutableMap<String, ActionDescriptor>> fActions;

  @Inject ActionRegistry(ThingRegistry thingRegistry) {
    ImmutableMap.Builder<Class<? extends Thing>, ImmutableMap<String, ActionDescriptor>> actionBuilder = ImmutableMap.builder();

    for (Class<? extends AbstractThing> cls : thingRegistry.getThingClasses().keySet()) {
      ImmutableMap.Builder<String, ActionDescriptor> classActionBuilder = ImmutableMap.builder();
      for (Method m : cls.getMethods()) {
        Action annotation = m.getAnnotation(Action.class);
        if (annotation != null) {
          Validate.isTrue(Modifier.isPublic(m.getModifiers()));
          Validate.isTrue(!Modifier.isStatic(m.getModifiers()));
          Validate.isTrue(!m.isVarArgs());

          Class<?>[] parameterTypes = m.getParameterTypes();
          Validate.isTrue(parameterTypes.length <= 1);

          Class<?> inputClass = null;
          if (parameterTypes.length == 1) {
            inputClass = parameterTypes[0];
            ensureHasPublicParameterlessConstructor(inputClass);
          }

          ActionDescriptor d = new ActionDescriptor(m, inputClass, annotation);
          classActionBuilder.put(toActionName(m.getName()), d);
        }
      }
      ImmutableMap<String, ActionDescriptor> classActions = classActionBuilder.build();
      if (!classActions.isEmpty()) {
        actionBuilder.put(cls, classActions);
      }
    }

    fActions = actionBuilder.build();
  }

  private static String toActionName(String methodName) {
    final String PREFIX = "do";
    Validate.isTrue(methodName.startsWith(PREFIX),
        "Action method name '%s' must start with '%s'.", methodName, PREFIX);
    return StringUtils.uncapitalize(methodName.substring(PREFIX.length()));
  }

  private static void ensureHasPublicParameterlessConstructor(Class<?> cls) {
    try {
      cls.getConstructor();
    } catch (NoSuchMethodException e) {
      throw new RuntimeException(e);
    }
  }

  public ActionDescriptor getActionDescriptorOrNull(Class<? extends Thing> thingClass, String actionName) {
    ImmutableMap<String, ActionDescriptor> classActions = fActions.get(thingClass);
    if (classActions == null) {
      return null;
    } else {
      return classActions.get(actionName);
    }
  }
}
